package db_servicer

import (
	"fmt"
	"regexp"

	"gopkg.in/rana/ora.v3"
)

/*
var ses *ora.Ses
var logger *log.Logger

*/

func DevicesList4User(p_user_id int) (dev []string) {

	// logger = log.New(os.Stdout, ">>>>>DB.Device List under specific user:", log.LstdFlags|log.Lshortfile)

	var v_flag int8
	var v_ret_msg string
	var v_data_msg string

	if _, err := ses.PrepAndExe("CALL pkg_user_info.Fetch_Device_List(:p1,:p2 , :p3, :p4   )",
		&v_flag, &v_ret_msg, &v_data_msg, int32(p_user_id)); err != nil {

		logPanic(fmt.Sprintf("***Panic in DevicesList4User, retMsg:%v, err: %v ***\n", v_ret_msg, err))
	}

	dev = regexp.MustCompile(" : ").Split(v_data_msg, -1)
	return

}

func Fetch_Continents_List() dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Fetch Continents List:", log.LstdFlags|log.Lshortfile)

	var v_flag int8
	var v_ret_msg string
	var v_data_msg string

	if _, err := ses.PrepAndExe("CALL pkg_user_info.Fetch_Continents_List(:p1,:p2 , :p3  )",
		&v_flag, &v_ret_msg, &v_data_msg); err != nil {

		logPanic(fmt.Sprintf("***Panic in Fetch_Continents_List, retMsg:%v, err: %v ***\n", v_ret_msg, err))
	}

	return dev_retMsg{Flag: v_flag,
		Message: v_ret_msg,
		Data:    v_data_msg,
	}

	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)
	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)

}

func Fetch_Child_Addr(p_parent_id int) dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Fetch Child Addr:", log.LstdFlags|log.Lshortfile)

	var v_flag int8

	var v_ret_msg string

	//	var v_data string //Lob
	procRset := &ora.Rset{}

	//	logger.Printf("\n=================&ora.Rset ==============================\n Type: %T ", procRset )

	stmtRefCall, err := ses.Prep("CALL  pkg_user_info.Fetch_Child_Addr(:p1,:p2, :p3, :p4)")
	defer stmtRefCall.Close()
	if err != nil {
		logPanic(fmt.Sprintf("***Panic in Fetch_Child_Addr(ses.Prep): %v ***\n", err))
	}

	_, err = stmtRefCall.Exe(&v_flag, &v_ret_msg, procRset, int32(p_parent_id))
	if err != nil {
		logPanic(fmt.Sprintf("***Panic in Fetch_Child_Addr(stmtRefCall.Exe), retMsg:%v, err: %v ***\n", v_ret_msg, err))
	}

	//	logger.Printf(">>> rowsAffected:%v, flag: %v, Msg: %v, procRset[%T]: %v",rowsAffected, v_flag,  v_ret_msg, procRset, procRset)
	////	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)
	//
	//		return dev_retMsg{ 1, "test", `{"Test":"test ..... " }`}
	//
	return Refcursor_to_string(v_flag, v_ret_msg, &procRset)
}

func FetchContries(p_continentCode string) dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Fetch Countries:", log.LstdFlags|log.Lshortfile)

	var v_flag int8

	var v_ret_msg string

	//	var v_data string //Lob
	procRset := &ora.Rset{}

	//	logger.Printf("\n=================&ora.Rset ==============================\n Type: %T ", procRset )

	stmtRefCall, err := ses.Prep("CALL  pkg_user_info.fetch_countries(:p1,:p2, :p3, :p4)")
	defer stmtRefCall.Close()
	if err != nil {
		logger.Panic(fmt.Sprintf("Panic, retMsg:%v, Error:%v\n", v_ret_msg, err))
	}

	_, err = stmtRefCall.Exe(&v_flag, &v_ret_msg, procRset, p_continentCode)
	if err != nil {
		logger.Panic(fmt.Sprintf("Panic, retMsg:%v, Error:%v\n", v_ret_msg, err))
	}

	//	logger.Printf(">>> rowsAffected:%v, flag: %v, Msg: %v, procRset[%T]: %v",rowsAffected, v_flag,  v_ret_msg, procRset, procRset)
	////	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)
	//
	//		return dev_retMsg{ 1, "test", `{"Test":"test ..... " }`}
	//
	return Refcursor_to_string(v_flag, v_ret_msg, &procRset)
}

func Fetch_Child_Addr_qry(p_parent_id int) dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Fetch Child Addr:", log.LstdFlags|log.Lshortfile)

	var v_flag int8

	var v_ret_msg string

	var v_data, v_child_addr string

	stmt, err := ses.Prep(fmt.Sprintf(` 
SELECT '{"addr_id":"'||addr_id||'","name":"'||name||'","py_inits":"'|| py_initials||'","admin_div_code":"'||admin_div_code||'","area_code":"'||area_code||'"}'  adr1 
from addr_code
where parent_id= %v `, p_parent_id), ora.OraS)

	defer stmt.Close()

	if err != nil {

		logPanic(fmt.Sprintf("***Panic in Fetch_Child_Addr_Qry, err: %v ***\n", err))
	}

	rst, err := stmt.Qry()
	//	logger.Printf("\n=======================================================\n%T: %v", rst,  rst)
	//	logger.Printf("\n=======================================================\n%T: %v", rst.Row,  rst.Row)
	for rst.Next() {

		//		logger.Printf("\n=======================================================\n%T: %v", rst.Row[0],  rst.Row[0])
		if v_child_addr == "" {
			v_child_addr += fmt.Sprintf("%v", rst.Row[0]) //.(ora.OraS)
		} else {
			v_child_addr += "," + fmt.Sprintf("%v", rst.Row[0]) // .(ora.OraS)
		}
	}
	if rst.Err != nil {
		logPanic(fmt.Sprintf("***Panic in Fetch_Child_Addr_qry, rst.Err: %v ***\n", rst.Err))

	}
	v_ret_msg = "已读取下级地址"

	v_data = fmt.Sprintf(`{"falg":0, "message":"%v","data":[%v"]}"`, v_ret_msg, v_child_addr)
	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data_msg)
	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)

	return dev_retMsg{Flag: v_flag,
		Message: v_ret_msg,
		Data:    v_data,
	}
}

func Modify_User_Alert_Num(p_user_id int, p_old_alert_num, p_new_alert_num int64) dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Modify User Alert Number:", log.LstdFlags|log.Lshortfile)

	var v_flag int8

	var v_ret_msg string

	var v_data string //Lob

	if _, err := ses.PrepAndExe("CALL  pkg_user_info.Modify_user_Alert_num(:p1,:p2 , :p3, :p4, :p5, :p6 )",
		//		 &v_flag, &v_ret_msg,  &v_data_msg, int32(p_parent_id) ); err != nil {
		&v_flag, &v_ret_msg, &v_data, int32(p_user_id), int64(p_old_alert_num), int64(p_new_alert_num)); err != nil {

		logger.Panic(fmt.Sprintf("Panic, retMsg:%v, Error:%v\n", v_ret_msg, err))
	}

	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)
	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)

	return dev_retMsg{Flag: v_flag,
		Message: v_ret_msg,
		Data:    v_data,
	}
}

func Modify_User_Addr(p_user_id, p_addr_id, p_country_id int, p_street_info string) dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Modify User Addr:", log.LstdFlags|log.Lshortfile)

	var v_flag int8

	var v_ret_msg string

	var v_data string //Lob

	if _, err := ses.PrepAndExe("CALL  pkg_user_info.Modify_user_Addr(:p1,:p2 , :p3, :p4, :p5, :p6, :p7 )",
		//		 &v_flag, &v_ret_msg,  &v_data_msg, int32(p_parent_id) ); err != nil {
		&v_flag, &v_ret_msg, &v_data, int32(p_user_id), int32(p_addr_id), int32(p_country_id), p_street_info); err != nil {

		logger.Panic(fmt.Sprintf("Panic, retMsg:%v, Error:%v\n", v_ret_msg, err))
	}

	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)
	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)

	return dev_retMsg{Flag: v_flag,
		Message: v_ret_msg,
		Data:    v_data,
	}
}

func Fetch_Child_Addr_bak(p_parent_id int) dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Fetch Child Addr:", log.LstdFlags|log.Lshortfile)

	var v_flag int8

	var v_ret_msg string

	var v_data string //Lob

	if _, err := ses.PrepAndExe("CALL  pkg_user_info.Fetch_Child_Addr(:p1,:p2 , :p3, :p4)",
		//		 &v_flag, &v_ret_msg,  &v_data_msg, int32(p_parent_id) ); err != nil {
		&v_flag, &v_ret_msg, &v_data, int32(p_parent_id)); err != nil {

		logger.Panic(fmt.Sprintf("Panic, retMsg:%v, Error:%v\n", v_ret_msg, err))
	}

	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)
	//	logger.Println(">>> flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data)

	return dev_retMsg{Flag: v_flag,
		Message: v_ret_msg,
		Data:    v_data,
	}
}

func Fetch_User_Info(p_user_id int) dev_retMsg {

	// logger = log.New(os.Stdout, ">>>>>DB.Fetch User Info:", log.LstdFlags|log.Lshortfile)

	var v_flag int8

	var v_ret_msg, v_data_msg string

	if _, err := ses.PrepAndExe("CALL  pkg_user_info.Fetch_User_Info(:p1,:p2 , :p3, :p4)",
		&v_flag, &v_ret_msg, &v_data_msg, int32(p_user_id)); err != nil {

		logger.Panic(fmt.Sprintf("Panic, retMsg:%v, Error:%v\n", v_ret_msg, err))
	}

	//	logger.Println(">>>user_id:", p_user_id , ",flag:", v_flag,  ",Msg:", v_ret_msg, "Data:", v_data_msg)

	return dev_retMsg{Flag: v_flag,
		Message: v_ret_msg,
		Data:    v_data_msg,
	}
}
